<?php use_javascript("chosen.jquery.min.js")?>
<?php use_stylesheet("main-css/chzn.css")?>
<?php
//echo 'here'; exit(); 
	$theme_color = ($the_directory->getThemeColor() != null && $the_directory->getThemeColor() != '') ? $the_directory->getThemeColor() : '#90cd67';
?>

<?php slot('custom_meta_tag') ?>
<?php echo html_entity_decode($custom_meta_tag)?>
<?php end_slot() ?>
 
<?php slot('meta_viewport') ?>
<?php if ($include_maps_api){?>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<?php }?>
<?php end_slot() ?>
						
<?php slot('google_maps') ?>
<?php if ($include_maps_api){?>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB5NDUuxqQcL2VYUp3G1qn_knSXAiCIXSI&sensor=false&language=es"></script>

<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];

var origin1 = '<?php echo $origin_city?>, <?php echo $origin_state?>';
var destination1 = '<?php echo $destination_city?>, <?php echo $destination_state?>';



function initialize() {

  geocoder = new google.maps.Geocoder();
}

function calculateDistances() {
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [origin1],
      destinations: [destination1],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,      

    }, callback);
}

function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var outputDiv = document.getElementById('outputDiv');
    outputDiv.innerHTML = '';
    deleteOverlays();

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
     // addMarker(origins[i], false);
      for (var j = 0; j < results.length; j++) {
          var distance_str  = results[j].distance.text;
          distance_str = distance_str.replace(".", "");
          distance_str = distance_str.replace(",", "");
          var distance = parseInt(distance_str);
         
         var a = <?php echo $price_formula_a?>;
         var b = <?php echo $price_formula_b?>;
         var price = a + (b*distance);

         var duration = results[j].duration.text;

         var duration_value = results[j].duration.value;

         duration_value_plus_20 = duration_value + (0.2 * duration_value);

         var duration_hours = Math.floor(duration_value_plus_20 / 3600) % 24;
         var duration_minutes = Math.floor(duration_value_plus_20 / 60) % 60;

         duration = duration_hours + "h " + duration_minutes + "min";
         
         
       
          

         var currency_symbol = '<?php echo $the_directory->getCurrencySymbol() != null ? $the_directory->getCurrencySymbol() : "$" ?>';
         <?php $language_id = $the_directory->getLanguageId();
         	   $travel_info_title = DirectoryUtils::getLabelTranslationByDecode("Travel Information", $language_id); 
         	   $distance = DirectoryUtils::getLabelTranslationByDecode("Distance between %s and %s", $language_id); 
         	   $time = DirectoryUtils::getLabelTranslationByDecode("Approximate Travel Time", $language_id); 
         	   $price = DirectoryUtils::getLabelTranslationByDecode("Approximate Travel Price", $language_id); 
         	   $weather = DirectoryUtils::getLabelTranslationByDecode("Weather in %s", $language_id); 
          ?>         

        var title_div = '<div class="travel_info_title"><?php echo $travel_info_title?></div>'  
   		var distance_div = '<article><p><?php echo sprintf($distance, $origin_city,  $destination_city) ?></p><h2>' + results[j].distance.text + '</h2></article>';
   		var price_div = '<article><p><?php echo $time ?></p><h2>' + duration + '</h2></article>';
   		var time_div = '<article><p><?php echo $price ?></p><h2>' + currency_symbol + " "  + price.toFixed(0) + '</h2></article>';
   		var weather_map_div = '<article><div id="weather_map_div"></div></article>';
        var clear_div = '<div style="clear:both"></div>';       
        outputDiv.innerHTML = '<div style="clear:both">' + distance_div + price_div + time_div  + '</div>' + clear_div;
        <?php 
	        $weather_arr = $sf_data->getRaw('weather_arr'); 
	        $current_condition = $weather_arr["data"]["current_condition"];
	        if (count($current_condition) > 0){
	   ?>
        	$("#weather_map_div").html("<div><?php  echo sprintf($weather, $destination_city)?></div>" + "<?php include_partial("weather", array("weather_arr" => $weather_arr)) ?>");
	   <?php      	
	        }
        ?>
         
      }
    }
  }
}



function deleteOverlays() {
  for (var i = 0; i < markersArray.length; i++) {
    markersArray[i].setMap(null);
  }
  markersArray = [];
}

google.maps.event.addDomListener(window, 'load', initialize);


    </script>	
<?php }?>	
<?php end_slot() ?>


<?php slot('google_maps_results')?>

<?php end_slot()?>

<?php 
	$template = Doctrine_Core::getTable ( 'Template' )->find($template_id);
	
?>


<?php slot('home') ?>
	<a href="http://<?php echo $the_directory->getDomain()?>"><?php echo $the_directory->getDomain()?></a>
<?php end_slot() ?>

<?php slot('title') ?>
	<?php echo $title_content?>
<?php end_slot() ?>

<?php slot('domain') ?>
<?php echo $the_directory->getDomain() ?>
<?php end_slot() ?>

<?php slot('rights') ?>
	<a style="font-size: 14px;text-decoration:none" href="http://<?php echo $the_directory->getDomain()?>"><?php echo $the_directory->getDomain()?></a>
<?php end_slot() ?>




<?php slot('meta_description') ?>

	<meta name="description" content="<?php echo $meta_description ?>" >

<?php end_slot() ?>

<?php slot('meta_google_verification') ?>
<?php if ($meta_google_verification != ""){?>
<meta name="google-site-verification" content="<?php echo $meta_google_verification?>" />
<?php } ?>
<?php end_slot() ?>

<?php slot('meta_keyword') ?>

	<meta  name="keywords" content="<?php echo $meta_kw ?>">

<?php end_slot() ?>




<?php //echo html_entity_decode($body_content) ?>

<?php 

$comment_tag = "##%%##comments##%%##";
$places_tag = "#%%#places_api_content#%%#";
$weather_tag = "#%%#weather_api#%%#";

$maps_tag = "#%%#maps_api#%%#";

$body_content = str_replace($weather_tag,'<div id="weather_div" style="clear:both"></div>', $body_content);

$body_content = str_replace($maps_tag,'<div id="outputDiv" style="clear:both"></div>', $body_content);

$body_arr = explode($comment_tag, $body_content, 2);
?>
<div style="clear:both">

<?php if ($json_arr != null){ 

	$body_bf_comments_bf_places = explode($places_tag, $body_arr[0]);
	?>
	<div style="clear:both">
	<?php 
	echo html_entity_decode($body_bf_comments_bf_places[0]);
	?>
	</div>
	<div style="clear:both"><?php include_partial("places", array("json_arr" => $json_arr)); ?> </div>
	
	<div style="clear:both">
	<?php 
	echo html_entity_decode($body_bf_comments_bf_places[1]);
	?>
	</div>
	<?php
	
} else {
	echo html_entity_decode($body_arr[0]);
}

?>




</div>

<?php 

if (count($body_arr) > 1){
	
	
	
	if ($template->getShowComments() == 1){
		?>

		<div style="clear:both">
			<?php 
			include_partial("comments/comments", array('comments' => $comments, 'comment_fields' => $comment_fields, 'template' => $template, 'category_content_ids' => $category_content_ids, 'show_rating' => $show_rating, 'directory' => $the_directory));
			?>
		</div>
	<?php }?>

		<div style="clear:both">
		
		<?php if ($json_arr != null){ 
		
			$body_after_comments_bf_places = explode($places_tag, $body_arr[1]);
			
			echo html_entity_decode($body_after_comments_bf_places[0]);
			include_partial("places", array("json_arr" => $json_arr));
			echo html_entity_decode($body_after_comments_bf_places[1]);
			
			
		}else{	
		 	echo html_entity_decode(str_replace($comment_tag, "", $body_arr[1]));
		}
		 ?>
		</div>
<?php }?>




<?php //exit(); //include_partial("weather", array("weather_arr" => $weather_arr))?>





<?php slot('footer') ?>
<?php if (count($footer_url) > 0){?>
<section id="footer-nav">
   <div class="container">
   <div class="col-sm-12">
	   <div class="box">
		<?php
		$uri = sfContext::getInstance()->getRequest()->getUri();
		$base_url = substr($uri, 0, strrpos($uri, '/') + 1);
		$base_url = str_replace("/index.php", "", $base_url);
		
		$raw_footer_url = $sf_data->getRaw('footer_url');
		$footer_count = count($raw_footer_url);
		
		if ($footer_count > 0){
		$chunk_size = $footer_count % 3 == 0 ?  $footer_count/3 : intval($footer_count/3) + 1;
		
		
		$chunked_arrs = array_chunk($raw_footer_url, $chunk_size);
		$i = 1;
		foreach ($chunked_arrs as $chunked_arr){
			?>
			<div class="col-sm-4">
			<?php 
			foreach ($chunked_arr as $url){
				?>
				<p>
					<a href="<?php echo $base_url . DirectoryUtils::slugify($url)?>.html"><?php echo str_replace('-', ' ', $footer_caption[$i-1])?></a>
				</p>
				<?php
				$i++; 
			}
			?>
			</div>
			<?php 
		}
		}
		?>
	 </div>
 </div>
 </div>
 </section>	
 <?php }?>
<footer>	
	<div class="container">
		<div class="col-sm-12">
			<span><?php include_slot('rights') ?> &copy; 2013 All rights reserved</span>
		</div>
	</div>
</footer>

<?php end_slot() ?>	


<?php slot('search') ?>

     <form action="<?php echo url_for("template_generation/search") ?>" method="post" name="form-control" id="search_form">
		<?php 
		
		$max_inclusive_variables = 0;
		$inclusive_variables = 0;
		$i = 0;

		
		foreach ($searchComponents as $searchComponent) {
			$level = $searchComponent[0];
			$variables = $searchComponent[1];
			
			if(count($variables) == 1){
				// exclusive
				?>
				<div id="Origen" class="form-group col-sm-5 no-padding-left no-padding-right">
				 <div class="col-sm-3">
				 	 <?php $category = $level->getCategory()?>
					 <label><?php echo $category->getName().": ";?></label>
				 </div>
					<?php 
					$contents = Doctrine_Core::getTable('CategoryContent')->getCategoryContentByLevel($level->getId());
					?>
				 <div class="col-sm-9 searchDrop">
					<select id="<?php echo str_replace(" ", "_", $variables[0]);?>" name="<?php echo str_replace(" ", "_", $variables[0]);?>" class="chzn-select form-control">
						<option value=""><?php echo $level->getName()?></option>
						<?php 
							foreach ($contents as $content) {
							?>
							<option value="<?php echo $content->getId();?>"><?php echo $content->getName();?></option>
							<?php 
							}
						?>
					</select>
				 </div>
				</div>
				<?php 
			}else{
			   // inclusive
			   ?>
			   
			   <div id="Origen" class="form-group col-sm-5 no-padding-left no-padding-right">
						<div class="col-sm-2">
						<?php $category = $level->getCategory()?>
							 <label><?php echo $category->getName().": ";?></label>
						</div>
						<?php 
				
						$contents = Doctrine_Core::getTable('CategoryContent')->getCategoryContentByLevel($level->getId());
						
						$inclusive_variables ++;
						?>
						<div class="col-sm-5">
						<select id="<?php echo str_replace(" ", "_", $variables[0]) ;?>" name="<?php echo str_replace(" ", "_", $variables[0]);?>" onchange="getChildrendata('<?php echo  str_replace(" ", "_", $variables[1])?>', $(this).attr('value'))" class="form-control">
						<option value=""><?php echo $level->getName()?></option>	
							<?php 
								foreach ($contents as $content) {
								?>
								<option value="<?php echo $content->getId();?>"><?php echo $content->getName();?></option>
								<?php 
								}
							?>
						</select>
						</div>
					
						<?php for ($i = 1; $i < count($variables); $i++) {
								$inclusive_variables++;
								//$onchange_param = $i + 2 < count($variables)-1 ?  $variables[$i+2] : "";
								$onchange_str = $i + 1 < count($variables)? "getChildrendata('". str_replace(" ", "_", $variables[$i+1]) ."', $(this).attr('value'))" : "";
								
							?>
								 
									<?php 
									$pieces = explode('.', $variables[$i]);
									//echo $pieces[count($pieces) - 1].": ";
									?>
								 <div class="col-sm-5">
									<select id="<?php echo str_replace(" ", "_", $variables[$i]);?>" name="<?php echo str_replace(" ", "_", $variables[$i]);?>" onchange="<?php echo $onchange_str?>" class="form-control">
											<option value=""><?php echo $pieces[count($pieces) - 1]?></option>
									</select>
								</div>
							</div>
							<?php 
						}?>
					
				
			   
			   <?php 
			}
			if($inclusive_variables > $max_inclusive_variables){
				$max_inclusive_variables = $inclusive_variables;
			}
			$inclusive_variables = 0;
		}
		
		$max_inclusive_variables = $max_inclusive_variables > 0 ? $max_inclusive_variables - 1 : 0;
		
		?>
		<div class="col-sm-2">
          <button type="button" class="btn btn-primary"><div style="float:left;"><div id="loading" style="display:none"><?php echo image_tag("loaders/loader.gif")?></div></div> <?php echo $the_directory->getSearchButtonCaption() ?></button>
        </div>

        	 <div id="error_msg" class="error_msg" style="clear:both; display: none; cursor:pointer;" onclick="$(this).hide('slow')">
				<div id="msg_text" ></div>
			</div>

	<div style="clear:both"></div>
	</form>	
	<div style="clear:both"></div>

	
<?php end_slot() ?>


<div id="refresh_script">

</div>

      
<?php slot('analytics_script') ?>
	<?php echo html_entity_decode($analytics_script) ?>
<?php end_slot() ?>


<?php slot('sitemap') ?>
<a href="http://<?php echo strtolower($the_directory->getDomain())?>/uploads/sitemap/<?php echo strtolower($the_directory->getDomain())?>/sitemap.xml" target="_blank">Sitemap</a>
<?php end_slot() ?>

<?php slot('fb_app_id'); echo trim($the_directory->getFbApp()); end_slot(); ?>


<script type="text/javascript">
$(".btn-primary").click(function(){
	validate_selection();
})
		function validate_selection(){
			var all_selected = true;
	        $("select").each(function()
	        		{
	    				var selected_value = $(this).attr("value");
	    				
	    				if (selected_value == ""){
							var name = $(this).attr("id");
							var name_arr = name.split(".");
							var end_str = name_arr[0];
							var start_str = name_arr[name_arr.length - 1];
							var start_str_arr = start_str.split("_");
							var select_str = "";
							for (var i = 0; i < start_str_arr.length; i++){
								select_str = select_str + " " + start_str_arr[i];
							}
							
							var error_msg = "<?php echo __("Please select")?> " + select_str ;
							$("#error_msg").show();
							$("#msg_text").html(error_msg);
							all_selected = false;
							return false;
		    			}
	        		    // add $(this).val() to your array
	        			//parent_arr.push($(this).parent().attr("id"));
	    				
	        		});
			
	       if (all_selected){
		       $('#loading').show();
		       if ( $.browser.msie ) {
		       		$('#loading').html('<?php echo image_tag("loaders/loader.gif")?>');
		       }
		       $('#search_div').html('<?php echo __("Searching")?>...');
		       /* _gaq.push(['_trackEvent', 'Search', 'Button', 'Button']);*/
				document.getElementById('search_form').submit();
	       }
		}

       function getChildrendata(childCombo, categoryContentId){
          // alert(categoryContentId); return false;
    	   var str="id=" + categoryContentId + "&name=" + childCombo;
    	   var refresh =  "refresh_script";
		    $.ajax({type: 'POST', url:' <?php echo url_for('template_generation/loadCategoryChildren')?>',  script:true, cache:false, data:  str,

	    	beforeSend: function(){
	            if (categoryContentId == ""){
		              var elem = document.getElementById(childCombo);
		              elem.options.length = 0; 
		              elem.options[0] = new Option('--<?php echo __("Select")?>--', '');
		              return false;
		        }

	       },
				
            success: function(data) {
	            var div_to_refresh = document.getElementById(refresh);
                 $(div_to_refresh).html(data);
               	 
             } });
           
       }

       $(document).ready(function() {
           var elem = document.getElementById("header"); 

           $(elem).css('height', $(elem).height() + <?php echo $max_inclusive_variables ?>  * 30);
			//LIKE A BOSSSSSSSSS
           <?php if (!$include_maps_api){
          	        $weather_arr = $sf_data->getRaw('weather_arr'); 
          	        $current_condition = $weather_arr["data"]["current_condition"];
          	        
          	        if (count($current_condition) > 0){
          	        	?>
           				$("#weather_div").html("<?php include_partial("weather", array("weather_arr" => $weather_arr)) ?>");
            	<?php        
            			}
            		}?>
           <?php if ($include_maps_api){?>
           calculateDistances();
           <?php }?>
           $(".chzn-select").chosen({ search_contains: true, max_selected_options: 3 });
           if (navigator.userAgent.indexOf("MSIE 10") > -1) {
         	    document.body.classList.add("ie10");
         	}
           if (navigator.userAgent.indexOf("MSIE 11") > -1) {
         	    document.body.classList.add("ie10");
         	}
    	 });
       
       
</script>
<!--<style>.search_div{padding:5px 0px;}.search_select{font-size:12px;width:214px}.error_msg{background:none repeat scroll 0 0 rgba(255,0,0,.1);border:1px solid rgba(255,0,0,.2);border-radius:4px 4px 4px 4px;color:rgba(255,0,0,.7);font-weight:bold;margin-top:7px;padding:2px 2px 2px 10px}.listing{margin-left:20px;margin-top:10px;line-height:20px}</style>
-->
<!--[if IE]>
<style>
.chzn-container-single .chzn-drop {top: 32px !important;}
.chzn-container-single .chzn-search input { width: 100% !important;}
.chzn-container-single .chzn-search {
    position: relative;
    margin: 0px;
	padding:0px!important;
    z-index: 1010;
    width: 100%;
	left:0px!important;
}
</style>
<![endif]-->
<style>
.ie10 .chzn-container-single .chzn-drop {top: 32px !important;}	
.ie10 .chzn-container-single .chzn-search input{ width: 100% !important;}   
.ie10 .chzn-container-single .chzn-search {
    position: relative;
    margin: 0px;
	padding:0px!important;
    z-index: 1010;
    width: 100%;
	left:0px!important;
}
</style>